import { GetServerSideProps } from "next";
import { memo, ReactElement } from "react";
import classNames from "classnames";
import wrapper from "@/store/index";
import { useDispatch } from "react-redux";
import { fetchSuggestList } from "@/store/modules/home";
import {
  getAllProduct,
  getHomeInfo,
  getHotProduct,
} from "@/services/modules/home";
import styles from "./index.module.scss";

import type { FC } from "react";
import type { IAppDispatch, IAppRootState } from "@/store/index";
import type {
  IBanner,
  ICategory,
  IDigital,
  IHotProduct,
  IProduct,
  IRecommend,
} from "@/services/modules/home";

import TopSwipper from "@/components/TopSwipper";
import SectionTitle from "@/components/SectionTitle";
import CategoryTab from "@/components/CategoryTab";
import Recommend from "@/components/Recommend";
import GridView4 from "@/components/GridView4";
import Digital from "@/components/Digital";

export interface IProps {
  children?: ReactElement;
  banners?: IBanner[];
  categorys: ICategory[];
  recommends?: IRecommend[];
  digitalData?: IDigital;
  hotProduct?: IHotProduct[];
  allProduct?: IProduct[];
}

const Home: FC<IProps> = memo(function (props) {
  // const { children } = props;
  const {
    banners = [],
    recommends = [],
    digitalData,
    categorys = [],
    hotProduct = [],
    allProduct = [],
  } = props;
  console.log(banners);

  const dispatch: IAppDispatch = useDispatch();
  return (
    <>
      <div className={styles.home}>
        {/* 走马灯 */}
        <TopSwipper banners={banners}></TopSwipper>
        {/* 类别 */}
        <CategoryTab categorys={categorys}></CategoryTab>
        {/* 推荐 */}
        <Recommend recommends={recommends}></Recommend>

        <div className={classNames("wrapper", styles.content)}>
          <SectionTitle title={"编辑推荐"}></SectionTitle>
          <GridView4 productList={hotProduct}></GridView4>

          <Digital digitalData={digitalData}></Digital>

          <SectionTitle title={"热门商品"}></SectionTitle>
          <GridView4 productList={allProduct}></GridView4>
        </div>
      </div>
    </>
  );
});

// 异步获取props
export const getServerSideProps: GetServerSideProps =
  wrapper.getServerSideProps(function (store) {
    return async (context) => {
      // 发起网络请求
      await store.dispatch(fetchSuggestList({}));
      // 获取首页数据
      const res = await getHomeInfo();
      // 获取推荐商品
      const res2 = await getHotProduct();
      // 获取所有商品
      const res3 = await getAllProduct();

      return {
        props: {
          banners: res.data.banners || [],
          categorys: res.data.categorys || [],
          recommends: res.data.recommends || [],
          digitalData: res.data.digitalData || [],

          hotProduct: res2.data.hotProduct || [],
          allProduct: res3.data.allProduct || [],
        },
      };
    };
  });

export default Home;
Home.displayName = "Home";
